/*
 * @Date: 2024-11-18 14:18:29
 * @LastEditors: kevinzgai zhanggai_ok@126.com
 * @LastEditTime: 2024-11-18 14:47:13
 * @FilePath: \movieShow2024\server\src\tasks.js
 */

import fetch from 'node-fetch';
import { database } from './db.js';

// 影片接口地址
const MOVIE_DATA_URL = 'https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&page_limit=50&page_start=0';

// 获取电影数据并插入数据库
export const fetchAndInsertMovies = async () => {
    try {
        console.log('开始获取电影数据...');
        const response = await fetch(MOVIE_DATA_URL, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
        });
        const data = await response.json();
        
        console.log(`获取到 ${data.subjects.length} 部电影`);
        
        // 插入电影数据
        for (const subject of data.subjects) {
            try {
                const movieData = {
                    id: subject.id,
                    title: subject.title,
                    description: `评分: ${subject.rate}`, // 可以根据需要修改描述
                    poster: subject.cover,
                    category: '热门', // 默认分类
                    rating: parseFloat(subject.rate),
                    releaseDate: new Date().toISOString(), // 由于API没有提供发布日期，使用当前日期
                    dateAdded: new Date().toISOString()
                };

                await database.addMovie(movieData);
                console.log(`成功添加电影: ${subject.title}`);
            } catch (error) {
                console.error(`添加电影失败 ${subject.title}:`, error);
            }
        }

        console.log("所有电影数据已插入数据库");
    } catch (error) {
        console.error("获取电影数据失败:", error);
        throw error;
    }
};

// 添加默认分类
export const addDefaultCategories = async () => {
    try {
        const defaultCategories = [
            { id: '1', name: '动作' },
            { id: '2', name: '喜剧' },
            { id: '3', name: '爱情' },
            { id: '4', name: '科幻' },
            { id: '5', name: '恐怖' },
            { id: '6', name: '动画' }
        ];

        for (const category of defaultCategories) {
            try {
                await database.addCategory(category);
                console.log(`添加分类: ${category.name}`);
            } catch (error) {
                // 忽略重复分类的错误
                if (!error.message.includes('UNIQUE constraint failed')) {
                    console.error(`添加分类失败 ${category.name}:`, error);
                }
            }
        }

        console.log("默认分类已添加");
    } catch (error) {
        console.error("添加默认分类失败:", error);
        throw error;
    }
};
